/**
 * This test takes a number up to 13 as an argument (assumes 2 by
 * default) and creates a multiple buffer strategy with the number of
 * buffers given.  This application enters full-screen mode, if available,
 * and flips back and forth between each buffer (each signified by a different
 * color).
 */

package com.eastmountain.chinese.fullscreen;

import java.awt.*;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;

import com.eastmountain.chinese.common.FlashCardLessonSet;
import com.eastmountain.chinese.db.flashcards.records.ChineseElementProperties;
import com.eastmountain.chinese.gui.HanZiDrawingSurface;
import com.eastmountain.util.Helpers;

public class SlideShow {
	
	private DisplayMode originalDisplayMode;
    
    private static Color[] COLORS = new Color[] {
        Color.red, Color.blue, Color.green, Color.white, Color.black,
        Color.yellow, Color.gray, Color.cyan, Color.pink, Color.lightGray,
        Color.magenta, Color.orange, Color.darkGray };

    private static DisplayMode[] BEST_DISPLAY_MODES = new DisplayMode[] {
        new DisplayMode(1280, 800, 32, DisplayMode.REFRESH_RATE_UNKNOWN ),
        new DisplayMode(1280, 800, 16, DisplayMode.REFRESH_RATE_UNKNOWN ),
        new DisplayMode(640, 480, 32, DisplayMode.REFRESH_RATE_UNKNOWN ),
        new DisplayMode(640, 480, 16, DisplayMode.REFRESH_RATE_UNKNOWN ),
        new DisplayMode(640, 480, 8, DisplayMode.REFRESH_RATE_UNKNOWN )
    };

    public static final int INDEX_WIDTH = 0;
    public static final int INDEX_HEIGHT = 1;
    public static final int INDEX_BITDEPTH = 2;
    public static final int INDEX_REFRESHRATE = 3;

    public static final String[] COLUMN_NAMES = new String[] {
        "Width", "Height", "Bit Depth", "Refresh Rate"
    };
    
    private static Font hanZiFont = new Font( "Arial Unicode MS", Font.PLAIN, 240 );
    
    Frame mainFrame;

    private static String japaneseString = "\u65e5\u672c\u8a9e\u6587\u5b57\u5217";
    
    public SlideShow() {
    }
    
    public void start( FlashCardLessonSet flashCardLessonSet ) {
    	
        GraphicsEnvironment env = null;
        GraphicsDevice device = null;
        int numBuffers = 2;
        
        ChineseElementProperties chineseElementProperties;
    	
        try {
        	
            env = GraphicsEnvironment.getLocalGraphicsEnvironment();
            device = env.getDefaultScreenDevice();
        	
            GraphicsDevice[] devices = env.getScreenDevices();
            originalDisplayMode = devices[0].getDisplayMode();
            printDisplayModeValues( originalDisplayMode );

            GraphicsConfiguration gc = device.getDefaultConfiguration();
            mainFrame = new Frame(gc);
            mainFrame.setUndecorated( true);
            mainFrame.setIgnoreRepaint(true);
            device.setFullScreenWindow(mainFrame);
            
            if (device.isDisplayChangeSupported()) {
                chooseBestDisplayMode(device); 
            }
            
            mainFrame.createBufferStrategy(numBuffers);
            BufferStrategy bufferStrategy = mainFrame.getBufferStrategy();
           
            while ( ( chineseElementProperties = flashCardLessonSet.nextFlashCard() ) != null ) {
            	
                for (int i = 0; i < numBuffers; i++) {
                	
                    Graphics g = bufferStrategy.getDrawGraphics();
                    
                    if (!bufferStrategy.contentsLost()) {
                    	
                    	//drawChineseElement( g, bufferStrategy,
                    	//		japaneseString.substring( k, k + 1 ) );
                    	drawChineseElement( g, bufferStrategy,
                    			chineseElementProperties.getChineseElement() );

                        g.dispose();
                        
                    }
                    
                    try {
                        Thread.sleep((int)1000);
                    } catch (InterruptedException e) {}
                    
                }
                
            }
            
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            device.setFullScreenWindow(null);
        }
        
    }

    private void drawChineseElement(Graphics g, BufferStrategy bufferStrategy,
    		String chineseElement) {

    	Graphics2D g2D = (Graphics2D) g;

    	int w = mainFrame.getWidth();
    	int h = mainFrame.getHeight();

    	g2D.setRenderingHint( RenderingHints.KEY_TEXT_ANTIALIASING,
    			RenderingHints.VALUE_TEXT_ANTIALIAS_ON );

    	g2D.setPaint( Color.BLACK );
    	g2D.fill( new Rectangle2D.Double(0, 0, w, h ) );

    	g2D.setFont( hanZiFont );
    	FontMetrics metrics = g2D.getFontMetrics( hanZiFont );

    	g2D.setColor( Color.BLACK );

    	GradientPaint redtowhite
    	= new GradientPaint( 0, 0, Color.RED,
    			w, h,
    			Color.WHITE );
    	g2D.setPaint( redtowhite );
    	Ellipse2D ellipse = new Ellipse2D.Double(0, 0, w, h );
    	g2D.fill( ellipse );

    	//showEllipsePoints( ellipse );

    	g2D.setColor( Color.BLACK );

    	g2D.setFont( hanZiFont );
    	metrics = g2D.getFontMetrics();
    	int textWidth = metrics.stringWidth( chineseElement );

    	Point point
    	= Helpers.calculateFieldPosition( g2D, chineseElement,
    			w, h, hanZiFont );
    	g2D.drawString( chineseElement,
    			point.x, point.y );

    	bufferStrategy.show();

    	//int translateWidth = (int) (w * (1 - scaleX)) / 2;

    	//g2D.translate( translateWidth, 0 );
    	//g2D.scale( scaleX, 1.0 );
    	//g2D.drawImage( bufferedImage, 0, 0, mainFrame );

}
    
    private static DisplayMode getBestDisplayMode(GraphicsDevice device) {
        for (int x = 0; x < BEST_DISPLAY_MODES.length; x++) {
            DisplayMode[] modes = device.getDisplayModes();
            for (int i = 0; i < modes.length; i++) {
                if (modes[i].getWidth() == BEST_DISPLAY_MODES[x].getWidth()
                   && modes[i].getHeight() == BEST_DISPLAY_MODES[x].getHeight()
                   && modes[i].getBitDepth() == BEST_DISPLAY_MODES[x].getBitDepth()
                   ) {
                    return BEST_DISPLAY_MODES[x];
                }
            }
        }
        return null;
    }
    
    public static void chooseBestDisplayMode(GraphicsDevice device) {
        DisplayMode best = getBestDisplayMode(device);
        if (best != null) {
            device.setDisplayMode(best);
        }
    }
    
    private void printDisplayModeValues( DisplayMode displayMode ) {
    	
        int bitDepth = displayMode.getBitDepth();
        int refreshRate = displayMode.getRefreshRate();
        String bd, rr;
        if (bitDepth == DisplayMode.BIT_DEPTH_MULTI) {
            bd = "Multi";
        } else {
            bd = Integer.toString(bitDepth);
        }
        if (refreshRate == DisplayMode.REFRESH_RATE_UNKNOWN) {
            rr = "Unknown";
        } else {
            rr = Integer.toString(refreshRate);
        }
        System.out.println( 
            COLUMN_NAMES[INDEX_WIDTH] + ": " + displayMode.getWidth() + " "
            + COLUMN_NAMES[INDEX_HEIGHT] + ": " + displayMode.getHeight() + " "
            + COLUMN_NAMES[INDEX_BITDEPTH] + ": " + bd + " "
            + COLUMN_NAMES[INDEX_REFRESHRATE] + ": " + rr
            );
    	
    	
    }
    
    public static void main(String[] args) {
        try {
            int numBuffers = 2;
            if (args != null && args.length > 0) {
                numBuffers = Integer.parseInt(args[0]);
                if (numBuffers < 2 || numBuffers > COLORS.length) {
                    System.err.println("Must specify between 2 and "
                        + COLORS.length + " buffers");
                    System.exit(1);
                }
            }
            
            //  TODO setup s FlashCardSet
            
            GraphicsEnvironment env = GraphicsEnvironment.
                getLocalGraphicsEnvironment();
            GraphicsDevice device = env.getDefaultScreenDevice();
            SlideShow test = new SlideShow();
            //test.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.exit(0);
    }
}
